package cn.com.anypay.manager.lakala.controller;

import cn.com.anypay.manager.lakala.response.CommonResp;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;

/**
 * 拉卡拉公钥获取控制器
 * 用于代理前端请求，解决CORS问题
 */
@RestController
@RequestMapping("/api/lakala")
public class LakalaPublicKeyController {

    private final RestTemplate restTemplate = new RestTemplate();
    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 获取拉卡拉公钥
     */
    @GetMapping("/public-key/{appId}")
    public CommonResp<?> getPublicKey(@PathVariable String appId) {
        Map<String, Object> result = new HashMap<>();
        result.put("appId", appId);

        // 测试多个环境
        Map<String, Object> responses = new HashMap<>();

        // 1. 测试环境
        try {
            String testUrl = "https://test.wsmsd.cn/sit/gw/pubcerts?appId=" + appId;
            responses.put("testEnv", fetchPublicKey(testUrl, "测试环境"));
        } catch (Exception e) {
            responses.put("testEnv", Map.of(
                "error", true,
                "message", e.getMessage()
            ));
        }

        // 2. 生产环境
        try {
            String prodUrl = "https://s2.lakala.com/gw/pubcerts?appId=" + appId;
            responses.put("prodEnv", fetchPublicKey(prodUrl, "生产环境"));
        } catch (Exception e) {
            responses.put("prodEnv", Map.of(
                "error", true,
                "message", e.getMessage()
            ));
        }

        // 3. 测试环境路径格式
        try {
            String testPathUrl = "https://test.wsmsd.cn/sit/gw/pubcerts/" + appId;
            responses.put("testPathEnv", fetchPublicKey(testPathUrl, "测试环境(路径格式)"));
        } catch (Exception e) {
            responses.put("testPathEnv", Map.of(
                "error", true,
                "message", e.getMessage()
            ));
        }

        result.put("responses", responses);

        // 分析结果
        boolean hasSuccess = false;
        String publicKey = null;
        for (Map.Entry<String, Object> entry : responses.entrySet()) {
            Map<String, Object> resp = (Map<String, Object>) entry.getValue();
            if (resp != null && !Boolean.TRUE.equals(resp.get("error"))) {
                String code = (String) resp.get("code");
                if ("000000".equals(code) || "0".equals(code)) {
                    hasSuccess = true;
                    publicKey = (String) resp.get("publicKey");
                    break;
                }
            }
        }

        if (hasSuccess && publicKey != null) {
            result.put("success", true);
            result.put("publicKey", publicKey);
            result.put("message", "成功获取公钥");
        } else {
            result.put("success", false);
            result.put("message", "所有环境均无法获取公钥，可能需要签名认证");
        }

        return CommonResp.createBySuccess(result);
    }

    /**
     * 实际请求拉卡拉API
     */
    private Map<String, Object> fetchPublicKey(String url, String envName) {
        Map<String, Object> result = new HashMap<>();
        result.put("url", url);
        result.put("environment", envName);

        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.add("Accept", "application/json");
            headers.add("User-Agent", "LakalaOpenAPI/3.0");

            HttpEntity<String> entity = new HttpEntity<>(headers);

            ResponseEntity<String> response = restTemplate.exchange(
                url,
                HttpMethod.GET,
                entity,
                String.class
            );

            result.put("statusCode", response.getStatusCode().value());
            result.put("body", response.getBody());

            // 解析响应
            if (response.getBody() != null) {
                Map<String, Object> bodyMap = objectMapper.readValue(response.getBody(), Map.class);
                result.put("code", bodyMap.get("code"));
                result.put("message", bodyMap.get("message"));

                // 如果有data字段，提取公钥
                if (bodyMap.containsKey("data")) {
                    result.put("data", bodyMap.get("data"));
                    // 这里可能需要进一步解析公钥内容
                }

                // 特殊处理错误码
                if ("GW0004".equals(bodyMap.get("code"))) {
                    result.put("authError", true);
                    result.put("errorDetail", "访问授权不通过 - 可能需要签名认证");
                }
            }

        } catch (Exception e) {
            result.put("error", true);
            result.put("errorMessage", e.getMessage());
            result.put("errorType", e.getClass().getSimpleName());
        }

        return result;
    }

    /**
     * 测试签名生成（后续使用）
     */
    @PostMapping("/test-signature")
    public CommonResp<?> testSignature(@RequestBody Map<String, String> params) {
        String appId = params.get("appId");
        String serialNo = params.get("serialNo");
        String privateKey = params.get("privateKey");

        Map<String, Object> result = new HashMap<>();
        result.put("appId", appId);
        result.put("serialNo", serialNo);
        result.put("message", "签名生成功能待实现");

        // TODO: 实现签名生成逻辑

        return CommonResp.createBySuccess(result);
    }
}
